package org.swim.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.swim.entity.Ability;
import org.swim.entity.User;
import org.swim.session.AbilityManagerRemote;
import org.swim.session.UserManagerRemote;

/**
 * Servlet implementation class SendAbilityRequest
 */
public class SendAbilityRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendAbilityRequest() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        int id = user.getId();
        InitialContext ic;
        try {
			ic = new InitialContext();
			AbilityManagerRemote abilityManager = (AbilityManagerRemote)ic.lookup("AbilityManagerRemote");
			UserManagerRemote userManager = (UserManagerRemote) ic.lookup("UserManagerRemote");
			List<Ability> definedAbilities = abilityManager.getAllDefinedAbility();
			List<Ability> abilities = new ArrayList<Ability>();
			for (Ability current: definedAbilities) {
				boolean exist = userManager.existingAbilityRequest(id, current.getIdAbilita());
				if(exist==false) {
					abilities.add(current);
				}
			}
			request.setAttribute("areThereAbilities", true);
			request.setAttribute("abilities", abilities);
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			request.setAttribute("areThereAbilities", false);
		}
        request.getRequestDispatcher("WEB-INF/AddAbilityRequest.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
